#include "socket.h"
using namespace std;

int make_client_socket()
{
    return socket(PF_INET, SOCK_DGRAM, 0);
}

int make_server_socket(int port_num)
{
    int sock_id;
    char host[HOSTLEN];
    struct sockaddr_in saddr;

    sock_id = socket(PF_INET, SOCK_DGRAM, 0);
    if (sock_id == -1)
    {
        return -1;
    }
    //Linux get host name 
    gethostname(host, HOSTLEN);
    if (make_internet_address(host, port_num, &saddr) == -1)
    {
        return -1;
    }
    if (bind(sock_id, (struct sockaddr *)&saddr, sizeof(saddr)) == -1)
    {
        return -1;
    }

    return sock_id;
}

int make_internet_address(char * host,int portnum,struct sockaddr_in * pSockaddr)
{
    struct hostent *hp;

    bzero((void *)pSockaddr, sizeof(struct sockaddr_in));
    hp = gethostbyname(host);
    if (hp == NULL)
    {
        return -1;
    }
    bcopy((void *)hp->h_addr, (void *)&pSockaddr->sin_addr, hp->h_length);
    pSockaddr->sin_port = htons(portnum);
    pSockaddr->sin_family = AF_INET;
    return 0;
}

int get_internet_address(char *host, int len, int *pPort, struct sockaddr_in *
pSocket)
{
    strncpy(host, inet_ntoa(pSocket->sin_addr), len);
    *pPort = ntohs(pSocket->sin_port);
    return 0;
}

void print_caller(struct sockaddr_in *sender)
{
    char host[HOSTLEN];
    int port;

    get_internet_address(host, HOSTLEN, &port, sender);
    printf("%s:%d\n", host, port);
}

void print_error(char *msg)
{
    fprintf(stderr, "Error: %s === %d\n", msg, getpid());
}

